'use strict';

const BaseService = require('./base');
const TreeData = require('../utils/tree_data');
const NotFoundException = require('../exception/not-found');

class AdminMenuService extends BaseService {


  async menuList(){
    const menus = await this.app.model.AdminMenu.findAll(
      {
        order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
        attributes: { exclude: [ 'delete_time' ] }
      }
    )
    return menus
  }

  async getMenuTree () {
    const menus = await this.app.model.AdminMenu.findAll({
      order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
      attributes: { exclude: [ 'delete_time' ] },
      // , 'create_time', 'update_time', 'api_route_name', 'icon', 'cache', 'affix', 'breadcrumb', 'remarks', 'sort'
    });
    const tree = new TreeData(menus.map(item => item.toJSON()), 'parent_id', 'id', 'children', []);
    return tree.getTree();
  }

  async findMenu (id) {
    const menu = await this.app.model.AdminMenu.findOne({ where: { id }, attributes: { exclude: [ 'delete_time' ] } });
    if (menu === null) {
      throw new NotFoundException('菜单不存在', 22000);
    }
    return menu;
  }

  async createMenu (body) {
    const params = this.app._.cloneDeep(body);
    params.create_time = new Date();
    await this.app.model.AdminMenu.create(params);
  }

  async updateMenu (body) {
    const params = this.app._.cloneDeep(body);
    delete params.id
    const menu = await this.findMenu(body.id);
    await menu.update(params);
  }

  async deleteMenu (ids) {
    const { Op } = this.app.Sequelize;
    await this.app.model.AdminMenu.destroy({
      where:{
        id:{
          [Op.in]:ids
        }
      }
    })
  }

  async changeStatus(params){
    const menus = await this.findMenus(params.ids);
    const updateStatus = []
    const length = menus.length;
    for(let i = 0;i<length;i++){
      const id = menus[i].get('id')
      const status = menus[i].get('status')
      let newStatus = status == 1?2:1
      updateStatus.push({id,status:newStatus})
    }
    if(updateStatus.length){
      await this.app.model.AdminMenu.bulkCreate(updateStatus,{updateOnDuplicate:['id','status']})
    }
  }

  async findMenus(Ids){
    const { Op } = this.app.Sequelize;
    const menus = await this.app.model.AdminMenu.findAll({
      where: {
        id: {[Op.in]: Ids}
      }
    });
    return menus
  }

}

module.exports = AdminMenuService;
